/*
 * queue.c
 *
 *  Created on: 2019年10月12日
 *      Author: duanj
 */
/* Includes ------------------------------------------------------------------*/
#include "stdlib.h"
#include "string.h"
#include "queue.h"


void QueueInit(Queue_TypeDef *queue)
{
	queue->Front = queue->Rear = NULL;
	queue->ItemCnt = 0;
}

int8_t QueueIsFull(const Queue_TypeDef *queue)
{
	if(queue->ItemCnt == MAX_QUEUE)
	{
		return 0;
	}
	else
	{
		return -1;
	}
}

int8_t QueueIsEmpty(const Queue_TypeDef *queue)
{
	if(queue->ItemCnt == 0)
	{
		return 0;
	}
	else
	{
		return -1;
	}
}

uint16_t QueueItemCount(const Queue_TypeDef *queue)
{
	return queue->ItemCnt;
}

int8_t EnQueue(Item_TypeDef item, Queue_TypeDef *queue)
{
	Node_TypeDef *new_node;
	
	if(QueueIsFull(queue) == 0)
	{
		return -1;
	}
	
	new_node = (Node_TypeDef *)malloc(sizeof(Node_TypeDef));
	if(new_node == NULL)
	{
		return -1;
	}
	memcpy((void *)(&(new_node->Item)), (const void *)(&item), sizeof(Item_TypeDef));
	new_node->Next = NULL;
	if(QueueIsEmpty(queue) ==  0)
		queue->Front = new_node;
	else
		queue->Rear->Next = new_node;
	queue->Rear = new_node;
	queue->ItemCnt++;
	
	return 0;
}

int8_t DeQueue(Item_TypeDef *item, Queue_TypeDef *queue)
{
	Node_TypeDef *node;
	
	if(QueueIsEmpty(queue) == 0)
	{
		return -1;
	}

	memcpy((void *)item, (const void *)(&(queue->Front->Item)) , sizeof(Item_TypeDef));
	node = queue->Front;
	queue->Front = queue->Front->Next;
	free(node);
	queue->ItemCnt--;
	if(queue->ItemCnt == 0)
		queue->Rear = NULL;

	return 0;
}

void EmptyTheQueue(Queue_TypeDef *queue)
{
	Item_TypeDef dummy;
	
	while(QueueIsEmpty(queue) == -1)
	{
		DeQueue(&dummy, queue);
	}
}


